from selenium import webdriver
import time
# from fake_useragent import UserAgent
import re
import random
import logging
# from ip_port import checkout_time
logger = logging.getLogger(__name__)
fh = logging.FileHandler('kuaipai.log')
sh = logging.StreamHandler()
logger.addHandler(fh)
logger.addHandler(sh)
logger.setLevel(logging.DEBUG)



class KuaiPai:

    def __init__(self, ip_port=0, keyword = '登录百度账号'):
        prefs = {
            'profile.default_content_setting_values': {
                'notifications': 2
            }
        }
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument('--window-size=1366,768')
        chrome_options.add_experimental_option('prefs', prefs) #禁止浏览器弹窗
        chrome_options.add_experimental_option('useAutomationExtension', False)
        chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])  # 去掉正在被自动化检测程序控制的提示
        # chrome_options.add_argument('user-agent={}'.format(UserAgent().random))
        # chrome_options.add_argument('--proxy-server=http://{}'.format(ip_port))
        # chrome_options.add_argument('--headless')
        self.driver = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=chrome_options)
        self.ip_port = ip_port
        self.keyword = keyword

    def get_interger(self, data):  # 转换数字
        try:
            res = int(data)
        except:
            try:
                res = float(data)
            except:
                res = data
        return res

    def is_empty(self, data):  # 处理数据为空的字段 str转int float
        if isinstance(data, list):
            if data != []:
                jieguo = data[0].strip()
                jieguo = self.get_interger(jieguo)
            else:
                jieguo = ''
        else:
            jieguo = self.get_interger(data)
        return jieguo

    def open_cookie_file(self,file, moshi):
        if moshi == 'a':
            with open(file, 'r') as f:
                con = f.read()
                lis = re.findall(r'.*?-+.*?-+(.*?)\n', con)
                return lis
        else:
            with open(file, 'r') as f:
                con = f.read()
                lis = con.split('\n')
                return lis

    def take_cookie(self):  # 添加cookies
        # cookies_list_1 = open_cookie_file('all2_cookies.json', 'a')
        # cookies_list_2 = open_cookie_file('all_cookies.json', 'b')
        cookies_list_3 = self.open_cookie_file('all3_cookies.json', 'b')
        self.driver.get("http://www.baidu.com")
        # 删除第一次建立连接时的cookie
        self.clear_cookie()
        # 读取登录时存储到本地的cookie
        while True:
            con = random.choice(cookies_list_3)
            lis = con.split(';')
            try:
                for i in lis:
                    i = i.split('=', 1)
                    self.driver.add_cookie({
                        'domain': '.baidu.com',  # 此处xxx.com前，需要带点
                        'name': i[0],
                        'value': i[-1],
                        'path': '/',
                        'expires': None
                    })
                #     listCookies = json.loads(f.read())
                self.driver.refresh()
                # time.sleep(5)
                # self.driver.get(
                #     "https://passport.baidu.com/v6/securitySettings/loginRecord?_t=1596596452&lang=zh-cn&gid=AA9DF4C-F580-40EF-ADBB-266BA9B435C7")
                break
            except Exception:
                logger.info('此cookie失效，已被记录！')
                with open('shixiao_coo.json', 'a') as f:
                    f.write(con + '\n')

    def clear_cookie(self):
        self.driver.delete_all_cookies()


    def open_baidu(self):
        # self.driver.maximize_window()
        time.sleep(2)
        self.driver.find_element_by_xpath("//input[@id='kw']").send_keys(self.keyword)
        time.sleep(3)
        baidu = self.driver.find_element_by_xpath("//input[@id='su']")
        baidu.click()
        self.driver.implicitly_wait(2)
        time.sleep(1)

    def click_one(self):
        a = self.driver.find_element_by_xpath('//*[@id="1"]/h3/a')
        time.sleep(1)
        a.click()
        time.sleep(3)
        self.driver.execute_script("window.scrollTo(0,300)")
        jilu = self.driver.find_element_by_xpath('//div[@class="li-line border-lighter clearfix"]/div[@class="mod-li-div left"]')
        jilu.click()

    def quit_chrome(self):
        time.sleep(10)
        self.driver.quit()

    def run(self):
        try:
            self.take_cookie()
            self.open_baidu()
            self.click_one()
        except Exception as e:
            print(e)
        finally:
            self.quit_chrome()

if __name__ == '__main__':
    # m = 0
    while True:
        kp = KuaiPai()
        kp.run()
        time.sleep(5)